package com.example.moviepro.controller;


import com.example.moviepro.entity.Comment;
import com.example.moviepro.service.CommentService;
import com.example.moviepro.service.MovieService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private MovieService movieService;

    @Autowired
    private CommentService commentService;

    // 添加评论:http://localhost:8080/comment/addComment
    @PostMapping("/addComment")
    public ResponseEntity<?> addComment(@Valid @RequestBody Comment comment,
                                        BindingResult result) {
        if (result.hasErrors()) {
            // 收集所有的错误信息
            List<String> errorMessages = result.getAllErrors().stream()
                    .map(error -> error.getDefaultMessage())
                    .collect(Collectors.toList());
            // 返回包含所有错误信息的响应
            return ResponseEntity.badRequest().body(errorMessages);
        }
        int movieId = comment.getMovieId();
        if(movieService.findMovieById(movieId) == null) {
            return ResponseEntity.badRequest().body("影片不存在");
        }
        commentService.addComment(comment);
        int com_id=commentService.findCommentId(comment);
        comment.setId(com_id);
        return ResponseEntity.ok(comment);
    }


    // 根据电影 ID 获取评论:http://localhost:8080/comment/getcomment/{movieId}
    @GetMapping("/getcomment/{movieId}")
    public ResponseEntity<List<Comment>> getCommentsByMovieId(@PathVariable int movieId) {
        if(movieService.findMovieById(movieId) == null) {
            //影片不存在
            return ResponseEntity.notFound().build();
        }
        List<Comment> comments = commentService.getCommentsByMovieId(movieId);
        if (!comments.isEmpty()) {
            return ResponseEntity.ok(comments);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据评论id删除评论:http://localhost:8080/comment/deleteComment/{id}
    @DeleteMapping("/deleteComment/{id}")
    public ResponseEntity<Void> deleteComment(@PathVariable int id) {
        Comment comment=commentService.findCommentById(id);
        if (comment != null) {
            commentService.deleteComment(id);
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
